package org.xml.create.DOM4J;

import java.io.FileOutputStream;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

public class DOM4JTest {

	public static void main(String[] args) throws IOException {
		newXMLByDOM4J();
	}

	private static void newXMLByDOM4J() throws IOException {
		// 1.通过DocumentHelper的createDocument方法创建Document对象
		Document document = DocumentHelper.createDocument();
		// 2.产生根节点并为根节点设置属性
		Element rss = document.addElement("rss");
		rss.addAttribute("version", "2.0");
		// 3.生成子节点和内容
		Element channel = rss.addElement("channel");// 为rss节点添加子节点channel
		Element title = channel.addElement("title");// 为channel节点添加子节点title
		title.addText("国内最新新闻");// 为title标签指定文本内容
		Element image = channel.addElement("image");
		Element imageTitle = image.addElement("title");
		imageTitle.addText("news.baidu.com");
		Element link = image.addElement("link");
		link.setText("http://news.baidu.com");
		Element url = image.addElement("url");
		url.setText("http://img.baidu.com/img/logo-news.gif");
		Element description = channel.addElement("description");
		description.setText("百度新闻订阅");
		Element item = channel.addElement("item");
		Element itemTitle = item.addElement("title");
		itemTitle.addCDATA("交通综合执法 用法治思维规范执法行为");
		Element pubDate = item.addElement("pubDate");
		pubDate.addCDATA("2015-02-13T07:53:57.000Z");

		// 4.设置生成XML文件的格式
		OutputFormat format = OutputFormat.createPrettyPrint();// 产生一个比较漂亮的格式
		format.setEncoding("gb2312");

		// 5.生成xml文件
		XMLWriter writer = new XMLWriter(new FileOutputStream(
				"rssnews_dom4j.xml"), format);
		 writer.setEscapeText(false);// 设置是否转义
		writer.write(document);// 将文档写入到输出流
		writer.close();
	}

}
